const router = require('koa-router')();
const cc = require('../conCtl');
const js = require('../jsCtl');
const db = require('../dbCtl');
const pc = require('../projectCtl');


/**
@hostpath = http://127.0.0.1/client/auction
 */

// const allAuction = async () => {
//   await pc.initSettings();//初始化环境变量
//   //获取所有拍卖活动数量
//   pc.storeAllAuction.auctionCount = await db.model('t_auction').where('state>0').count();
//   //获取拍卖活动
//   let auction = await db.model('t_auction').where('state>0').select();
//   for (let i = 0; i < auction.length; i++) {
//     //处理所有拍卖活动的图片
//     auction[i].img = auction[i].img.split(';');
//     if (auction[i].state == 1) { //当前拍卖活动未开始
//       //获取当前拍卖活动的所有拍卖商品
//       auction[i].goods = await db.model('t_auction_goods').where('auction_id=?', auction[i].id).select();
//     } else { //当前拍卖活动进行中或者已结束


//     }
//   }
//   pc.storeAllAuction.auction = auction;
//   cc.log(pc.storeAllAuction);
// }

// allAuction();



//一个拍卖活动有x个商品,有y轮
//每一轮拍卖3个商品,y=x/3 + (x%3==0?0:1)
//每轮拍卖3分钟

//新增表
//表1 拍卖出价纪录表

//机器人定时器自动出价
//在当前拍卖价低于当前商品的保护价时,机器人连续出价直到大于等于当前商品保护价
//判断当前商品在1秒内是否有人或者机器人出价,如果有则不允许出价


/** 获取拍卖列表
###
    GET {{hostpath}}?page=1&size=30
### */
router.get('/', async c => {
  let
    page = c.query.page || 1,
    size = c.query.size || 10

  let model = db.model('t_auction a').where('state>0');

  let data = await model.orderBy('dt desc').field('a.id,a.state,a.name,a.img,a.dt,(select count(1) from t_auction_goods where auction_id=a.id) as `count`').select(page, size);
  for (let i = 0; i < data.length; i++) {
    const element = data[i];
    element.img = element.img.substring(0, element.img.lastIndexOf(';')).split(';');
  }
  let banner = await db.model('t_banner').where('state', 1).select();
  cc.send_list(c, { 'data': data, 'banner': banner });
});

/** 获取正在拍卖的拍卖活动详情数据
###
    POST {{hostpath}}/having
    Content-Type: application/json

    {
        "id":"1"
    }
### */
router.post('/having', async c => {

  if (!pc.storeAllAuction.auctionList[c.request.body.id]) js.throwObj('未找到拍卖活动', js.rescode.no_result);

  // let state = await db.model('t_auction').where('id=?', c.request.body.id).shift('未找到拍卖活动', 'state');
  // if (state == 3 || state == 1) js.throwObj('暂无数据', js.rescode.no_result);
  let offer_prize = js.cloneObject(pc.storeAllAuction.auctionList[c.request.body.id].curGoods);
  if (offer_prize.length == 0) js.throwObj('暂无数据', js.rescode.no_result);
  //正在拍卖的出价纪录数据
  // for (let i = 0; i < offer_prize.length; i++) {
  //   //商品热度+1
  //   // await db.model('t_auction_goods').where('auction_goods_id=?', offer_prize[i].auction_goods_id).updateSql('view=view+?', 1);
  //   // offer_prize[i].details = offer_prize[i].details.split(';')[0];//todo...
  //   // offer_prize[i].state = 2;//todo...
  //   //出价次数
  //   /**offer_prize[i].count = await db.model('t_auction_log').where('auction_goods_id=?', offer_prize[i].auction_goods_id).count();
  //   if (offer_prize[i].count == 0) {
  //     offer_prize[i].list.push({ offer_price: 0, offer_type: 2 });
  //   }
  //   offer_prize[i].list = await db.model('t_auction_log')
  //     .where('auction_goods_id=?', offer_prize[i].auction_goods_id)
  //     .field('offer_type,offer_openid,offer_price')
  //     .orderBy('dt desc')
  //     .shift();
  //   if (!js.isNullOrUndefined(offer_prize[i].list.offer_type)) {
  //     if (offer_prize[i].list.offer_type == 1) {//最后一次出价的人是用户
  //       offer_prize[i].list.user = await db.model('t_users').where('openid=?', offer_prize[i].list.offer_openid).shift('', 'nick');
  //       offer_prize[i].list.headurl = await db.model('t_users').where('openid=?', offer_prize[i].list.offer_openid).shift('', 'headurl');
  //     } else {//最后一次出价的人是机器人
  //       offer_prize[i].list.user = await db.model('t_robot').where('id=?', offer_prize[i].list.offer_openid).shift('', 'nick');
  //       offer_prize[i].list.headurl = await db.model('t_robot').where('id=?', offer_prize[i].list.offer_openid).shift('', 'headurl');
  //     }
  //   }*/
  // }


  cc.send_list(c, offer_prize);
});

/** 获取即将拍卖的拍卖活动详情数据
###
    POST {{hostpath}}/soon
    Content-Type: application/json

    {
        "id":"2"
    }
### */
router.post('/soon', async c => {
  if (!pc.storeAllAuction.auctionList[c.request.body.id]) js.throwObj('未找到拍卖活动', js.rescode.no_result);

  let offer_prize = js.cloneObject(pc.storeAllAuction.auctionList[c.request.body.id].goods);
  if (offer_prize.length == 0) js.throwObj('暂无数据', js.rescode.no_result);



  // await db.model('t_auction').where('id=?', c.request.body.id).shift('未找到拍卖活动');
  // let offer_prize = await db.model('t_auction_goods a')
  //   .join('t_goods b on a.goods_id=b.id')
  //   .where('a.state=1&&a.auction_id=?&&b.state>0', c.request.body.id)
  //   .field('a.auction_goods_id,b.name,b.details,b.starting_price,b.svaha_price,b.bid_increment,a.goods_id,a.view')
  //   .orderBy('a.sort')
  //   .select();
  // for (let i = 0; i < offer_prize.length; i++) {
  //   //商品热度+1
  //   // await db.model('t_auction_goods').where('auction_goods_id=?', offer_prize[i].auction_goods_id).updateSql('view=view+?', 1);
  //   offer_prize[i].details = offer_prize[i].details.split(';')[0];
  // }

  cc.send_list(c, offer_prize);
});



/** 拍卖人列表
###
    POST {{hostpath}}/list
    Content-Type: application/json

    {
        "auction_goods_id":"5"
    }
### */
router.post('/list', async c => {
  let data = await db.start('SELECT x.*, z.`name`,z.details,z.id as goods_id FROM ( ' +
    'SELECT b.offer_id, b.auction_goods_id, a.nick, a.headurl, b.offer_price, b.dt FROM t_users a LEFT JOIN t_auction_log b ON a.openid = b.offer_openid WHERE b.auction_goods_id =? AND b.offer_type = 1 ' +
    'UNION ' +
    'SELECT b.offer_id, b.auction_goods_id, a.nick, a.headurl, b.offer_price, b.dt FROM t_robot a LEFT JOIN t_auction_log b ON a.id = b.offer_openid WHERE b.auction_goods_id =? AND b.offer_type = 2 ' +
    ') x LEFT JOIN t_auction_goods y ON x.auction_goods_id = y.auction_goods_id LEFT JOIN t_goods z ON y.goods_id = z.id ' +
    'ORDER BY x.dt DESC', [c.request.body.auction_goods_id, c.request.body.auction_goods_id]);
  for (let i = 0; i < data.length; i++) {
    data[i].details = data[i].details.split(';')[0];
  }
  cc.send(c, data);
});


/** 商品详情
###
    POST {{hostpath}}/goodsdetail
    Content-Type: application/json

    {
        "goods_id":"7"
    }
### */
router.post('/goodsdetail', async c => {
  let data = await db.model('t_goods a').join('t_auction_goods b on a.id=b.goods_id').where('a.id=?', c.request.body.goods_id).field('a.*,b.security').shift('未找到商品');
  //商品热度+1
  await db.model('t_auction_goods').where('goods_id=?', c.request.body.goods_id).updateSql('view=view+?', 1);
  cc.send(c, data);
});

/** 梭哈商品
###
    POST {{hostpath}}/svaha
    Content-Type: application/json

    {
        "auction_goods_id":5,
        "svaha_price":1
    }
### */
router.post('/svaha', async c => {
  js.check_params(
    !c.request.body.auction_goods_id && '!竞拍商品');

  let data1 = await db.model('t_auction_log')
    .where('auction_goods_id=?', c.request.body.auction_goods_id)
    .orderBy('dt desc')
    .shift();
  let data = await db.model('t_auction_goods a')
    .join('t_goods b on a.goods_id=b.id')
    .where('a.auction_goods_id=?&&a.state=3', c.request.body.auction_goods_id)
    .field('b.svaha_price,b.bid_increment')
    .shift('商品已被拍');
  if (!js.isNullOrUndefined(data1.offer_price)) {
    //有人出价
    //判断当前梭哈人的梭哈价小于最先出价人的出价,则梭哈人的价格为最新出价加该商品加价幅度
    if (c.request.body.svaha_price < data1.offer_price) {
      data.svaha_price = data1.offer_price + data.bid_increment;
    }
  } else {
    //无人出价
    data.svaha_price = data.bid_increment;
  }

  //当前用户openid
  // let openid = c.session.user.id;
  let openid = 'oM2uY59aMmztLxDeqN2hC8fcCo8c';

  //新增当前梭哈人出价纪录
  let log_id = await db.model('t_auction_log')
    .insert({ auction_goods_id: c.request.body.auction_goods_id, offer_type: 1, offer_openid: openid, offer_price: data.svaha_price });
  //修改该竞拍商品的最终成交价以及中拍人ID、该竞拍活动的商品状态已结束
  let auction_goods_id = await db.model('t_auction_goods')
    .where('auction_goods_id=?', c.request.body.auction_goods_id)
    .update({ final_price: data.svaha_price, winner_openid: openid, state: 3 });
  cc.send(c, { 'log_id': log_id, 'auction_goods_id': auction_goods_id });
});

/** 商品出价
###
    POST {{hostpath}}/offer
    Content-Type: application/json

    {
        "auction_goods_id":1,
        "openid":"oM2uY59aMmztLxDeqN2hC8fcCo8c",
        "auction_id":"1"
    }
### */
router.post('/offer', async c => {
  js.check_params(
    !c.request.body.auction_goods_id && '!竞拍商品');
  let rate = await db.model('t_users').where('openid=?', c.request.body.openid).shift('', 'payment_rate');
  if (rate < 70)
    js.throwObj('您需要先缴纳保证金!', js.rescode.bond);
  let auction_goods_id = c.request.body.auction_goods_id;

  // let auction = pc.storeAllAuction.auctionList[c.request.body.auction_id];
  let goods = await db.model('t_auction_goods a').join('t_goods b on a.goods_id = b.id')
    .where('a.auction_goods_id=?', c.request.body.auction_goods_id)
    .shift();

  let log = await db.model('t_auction_log')
    .where('auction_goods_id=?', auction_goods_id)
    .orderBy('offer_id desc,dt desc')
    .shift();
  let price = 0;
  if (!js.isNullOrUndefined(log.offer_price)) {
    price = log.offer_price + goods.bid_increment;
  } else {
    price = goods.starting_price + goods.bid_increment;
  }
  await db.model('t_auction_log').insert({ auction_goods_id: auction_goods_id, offer_type: 1, offer_openid: c.request.body.openid, offer_price: price });
  // pc.storeAllAuction.auctionList[c.request.body.auction_id].goods.last_offer_time = (new Date()).getTime();
  cc.send(c);

});

/** 缴纳保证金
###
    POST {{hostpath}}/offer
    Content-Type: application/json

    {
        "auction_goods_id":1
    }
### */
router.post('/offer', async c => {
  js.check_params(
    !c.request.body.auction_goods_id && '!竞拍商品');

  cc.send(c);

});


module.exports = router;